package com.quanta.edaily.config.exception;

import com.quanta.edaily.bean.JsonResponse;
import com.quanta.edaily.bean.contants.ResultCode;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import jakarta.validation.ValidationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.net.BindException;
import java.util.stream.Collectors;

@Slf4j
@ControllerAdvice
public class MyExceptionHandler { // 自定义异常处理

    @ExceptionHandler(ServiceException.class)
    @ResponseBody
    public JsonResponse service(ServiceException se) {
        log.error("义务类异常", se);
        return JsonResponse.error(se.getCode(), se.getMessage());
    }

    @ExceptionHandler({BindException.class, ValidationException.class, MethodArgumentNotValidException.class})
    @ResponseBody
    public JsonResponse validate(Exception e) {
        JsonResponse resp;
        log.error("数据校验异常", e);
        if (e instanceof MethodArgumentNotValidException) {
            // BeanValidation exception
            MethodArgumentNotValidException ex = (MethodArgumentNotValidException) e;
            resp = JsonResponse.error(ResultCode.PARAM_ERROR,
                    ex.getBindingResult().getAllErrors().stream()
                            .map(ObjectError::getDefaultMessage)
                            .collect(Collectors.joining("; "))
            );
        } else if (e instanceof ConstraintViolationException) {
            // BeanValidation GET simple param
            ConstraintViolationException ex = (ConstraintViolationException) e;
            resp = JsonResponse.error(ResultCode.PARAM_ERROR,
                    ex.getConstraintViolations().stream()
                            .map(ConstraintViolation::getMessage)
                            .collect(Collectors.joining("; "))
            );
        }
        else if (e instanceof BindException) {
            // BeanValidation GET object param
            BindException ex = (BindException) e;
            resp = JsonResponse.error(ResultCode.PARAM_ERROR,
                        ex.getMessage()
//                    ex.getAllErrors().stream()
//                            .map(ObjectError::getDefaultMessage)
//                            .collect(Collectors.joining("; "))
                        );
        } else resp = JsonResponse.error(ResultCode.PARAM_ERROR, e.getMessage());
        return resp;
    }

//    @ExceptionHandler(Exception.class) // 全局异常处理
//    @ResponseBody
//    public JsonResponse globalException(Exception e) {
//        e.printStackTrace();
//        return JsonResponse.systemError("系统错误");
//    }
}
